package com.woquyin.interceptor;

import java.util.Calendar;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.woquyin.common.Constance;
import com.woquyin.controller.api.IndexController;
import com.woquyin.model.SecUser;
import com.woquyin.vo.ReturnData;

public class ApiAuthInterceptor implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		String requestType = c.getRequest().getHeader("X-Requested-With");
		
		SecUser loginedUser = SecUser.dao.findUserById("6342d4af17dc492aa5c987c273910716");
		c.getSession().setAttribute("userInfo", loginedUser);
//		SecUser loginedUser = (SecUser)c.getSession().getAttribute("userInfo");
		
		if(requestType != null){
			asynchronous(inv, loginedUser, c);
		}else{
			synchronization(inv, loginedUser, c);
		}
	}
	
	public void asynchronous(Invocation inv, SecUser loginedUser, Controller c){
		ReturnData<SecUser> resp = new ReturnData<SecUser>();
		if (loginedUser != null) {
			String status = SecUser.dao.findStatusById(loginedUser.getId());
			if (Constance.UserStatus.BE_FROZEN.equals(status)) {
				loginedUser.setStatus(status);
				resp.setCode(Constance.UserStateCodeEnum.BE_FROZEN.getCode());
				resp.setMsg(Constance.UserStateCodeEnum.BE_FROZEN.getValue());
				c.renderJson(resp);
			} else {
				inv.invoke();
			}
		} else {
			resp.setCode(Constance.UserStateCodeEnum.LOGIN_ERROR.getCode());
			resp.setMsg(Constance.UserStateCodeEnum.LOGIN_ERROR.getValue());
			c.renderJson(resp);
		}
	}
	
	public void synchronization(Invocation inv, SecUser loginedUser, Controller c){
		if (loginedUser != null) {
			String status = SecUser.dao.findStatusById(loginedUser.getId());
			if (Constance.UserStatus.BE_FROZEN.equals(status)) {
				loginedUser.setStatus(status);
				c.redirect("/index");
			} else {
				inv.invoke();
			}
		} else {
			c.redirect("/index");
		}
	}

}
